package com.ylbh.modules.accessory.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.ylbh.common.pojo.goods.dto.GoodsDTO;
import com.ylbh.common.pojo.goods.dto.GoodsImgDTO;
import com.ylbh.common.pojo.goods.dto.SpecPropertyDTO;
import com.ylbh.common.pojo.goodsorder.vo.OrderOrAddressVO;
import com.ylbh.common.pojo.goodsorder.vo.ShoppingExpressCompanyVO;
import com.ylbh.common.pojo.goodsorder.vo.SubOrderListVO;
import com.ylbh.common.pojo.hn.vo.HNSpecVO;
import com.ylbh.common.utils.*;
import com.ylbh.modules.accessory.*;
import com.ylbh.modules.accessory.entity.HNExpressCallback;
import com.ylbh.modules.accessory.entity.HNGoodsPrice;
import com.ylbh.modules.accessory.entity.HNSpec;
import com.ylbh.modules.accessory.service.HLGoodsService;
import com.ylbh.modules.goods.mapper.ShoppingGoodsMapper;
import com.ylbh.modules.goods.service.GoodsSpecService;
import com.ylbh.modules.goods.service.ShoppingGoodsService;
import com.ylbh.modules.goodsorder.mapper.ShoppingOrderFormMapper;
import net.sf.json.JSONArray;
import org.apache.commons.lang.StringEscapeUtils;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.DecimalFormat;
import java.util.*;
import java.util.regex.Pattern;

/**
 * @author: czx
 * @date: 2019/11/22 09:59
 */
@Service
public class HLGoodsServiceImpl implements HLGoodsService {

    private final Logger log = LoggerFactory.getLogger(HLGoodsServiceImpl.class);

    @Autowired
    private ShoppingGoodsMapper shoppingGoodsMapper;

    @Autowired
    private GoodsSpecService goodsSpecService;

    @Autowired
    private ShoppingGoodsService shoppingGoodsService;

    @Autowired
    private ShoppingOrderFormMapper shoppingOrderFormMapper;

    @Value("${url.addEsGoods}")
    private String addEsGoods;

    @Value("${url.removeEsGoods}")
    private String removeEsGoods;

    @Value("${url.hnUrl}")
    private String hnUrl;

    @Value("${url.clientId}")
    private String clientId;

    @Value("${url.clientToken}")
    private String clientToken;

    @Value("${url.deliverGoods}")
    private String deliverGoods;

    @Value("${url.kdniao}")
    private String kdniao;

    /**
     * 商品上架
     * @param dto
     */
    @Override
    public void goodsShelve(HNDTO dto) {
//        String sign = DigestUtils.md5Hex(dto.getRequestData()+CLIENTTOKEN).toUpperCase();
//        if (!dto.getDataSign().equals(sign)) {
//            return;
//        }
//        JSONObject jsonObject = JSON.parseObject(dto.getRequestData());
//        Object data = jsonObject.get("data");
        HNExpressCallback hnExpressCallback = FastJsonUtil.toBean(dto.getData(), HNExpressCallback.class);
//        String goodsSku1 = jsonObject.getString("goodsSku");
//        String goodsSku = jsonObject.getString(data.toString());
        String goodsSku = hnExpressCallback.getGoodsSku();
        switch (dto.getRequestType()) {
            case "goods.shelve":
                // 商品上架
                // 根据候鸟的sku来上下架商品
                shoppingGoodsMapper.updateGoodsShelve(goodsSku, 0);
                int goodsId = shoppingGoodsMapper.selectGoodsIdBySku(goodsSku);
                HashMap<String, String> map = new HashMap<>();
                map.put("id", goodsId + "");
                String httpPost = HttpClientHelperUtils.sendHttpPost(addEsGoods, map);
                log.info("=============================上架商品添加到es服务器返回信息:" + httpPost);
                break;
            case "goods.unshelve":
                // 商品下架
                // 根据候鸟的sku来上下架商品
                shoppingGoodsMapper.updateGoodsShelve(goodsSku, -2);
                int goodsId2 = shoppingGoodsMapper.selectGoodsIdBySku(goodsSku);
                HashMap<String, String> map2 = new HashMap<>();
                map2.put("id", goodsId2 + "");
                String httpPost2 = HttpClientHelperUtils.sendHttpGet(removeEsGoods, map2);
                log.info("=============================下架商品同时删除es商品信息：" + httpPost2);
                break;
            case "goods.price":
                // 价格变更
                getHNGoodsDetails(goodsSku);
                break;
            case "order.delivery":
                // 订单发货
//                Map<String, Object> jsonObject1 = JSONObject.parseObject(dto.getData());
//                hnDeliverGoods(jsonObject1);
                hnDeliverGoods(hnExpressCallback);
                break;
            case "goods.edit":
                // 商品更新
                getHNGoodsDetails(goodsSku);
                break;
            case "goods.stock":
                // 商品库存
                getHNGoodsDetails(goodsSku);
                break;
            default:
                break;
        }
    }

    public String getHNGoodsDetails(String sku) {
        HashMap<String, String> m = new HashMap<>();
        m.put("clientId", clientId);
        m.put("clientToken", clientToken);
        m.put("method", "goods.getGoodsDetailBySku");
        m.put("goodsSku", sku);
        String sss = HttpUtils.sendPost(hnUrl, m);
        com.alibaba.fastjson.JSONObject jsonObject1 = JSON.parseObject(sss);
        JSONObject data = jsonObject1.getJSONObject("data");
        HouNiao hn = FastJsonUtil.toBean(data.getString("goodsDetail"), HouNiao.class);
        GoodsDTO dto = new GoodsDTO();
        dto.setGoodsSerial(hn.getSku());
        // 根据sku查询商品id
        int goodsId = shoppingGoodsMapper.selectGoodsIdBySku(dto.getGoodsSerial());
        dto.setId(Integer.valueOf(goodsId).longValue());
        dto.setGoodsName(hn.getGoodsName());
        JSONObject spec = JSON.parseObject(hn.getSpec().get(0));
        String hnSpec = "";
        for (Map.Entry<String, Object> entry : spec.entrySet()) {
            hnSpec = entry.getKey();
            break;
        }
//        String specJSONObject = spec.getString("基准");
        String specJSONObject = spec.getString(hnSpec);
        List<HNSpec> specs = FastJsonUtil.toList(specJSONObject, HNSpec.class);
        if (null != specs && specs.size() > 0) {
            List list = new ArrayList<GoodsInventoryDetailsToJsons>();
            // 售价
            BigDecimal buyerPrice = null;
            // 商品库存
            int stock = 0;
            for (HNSpec s : specs) {
                // 根据候鸟的规格名去查询数据库中是否存在该规格
                List<Integer> specId = goodsSpecService.getIsExistenceByName(s.getSpecDesc());
                GoodsInventoryDetails gidtj = new GoodsInventoryDetails();
                if (specId.size() > 0) {
                    // 说明数据库中已然存在同样的规格名
                    if (null == specId.get(0)) {
                        return "规格为空";
                    }
                    gidtj.setId(specId.get(0) + "_");
                } else {
                    // 否则没有需要新建规格
                    SpecPropertyDTO spdto = new SpecPropertyDTO();
                    spdto.setSpecId(32797);
                    spdto.setName(s.getSpecDesc());
                    goodsSpecService.addSpec(spdto, new Date());
                    if (null == spdto.getId()) {
                        // 如果插入都没有返回id就去查
                        spdto = goodsSpecService.selectSpecIdByName(spdto);
                        if (null == spdto.getId()) {
                            return "新增规格为空";
                        }
                    }
                    gidtj.setId(spdto.getId() + "_");
                }

                // 取出最小的
                if (null == buyerPrice) {
                    buyerPrice = new BigDecimal(s.getSpecPrice());
                } else {
                    if (buyerPrice.compareTo(new BigDecimal(s.getSpecPrice())) == 1) {
                        buyerPrice = new BigDecimal(s.getSpecPrice());
                    }
                }
                if (stock == 0) {
                    stock = Integer.parseInt(s.getStock());
                }
                gidtj.setPriceType("2");
                gidtj.setCount(s.getStock());
                gidtj.setImgPath(hn.getPicLibUrl() + hn.getTiny());
                gidtj.setBuyerPrice(s.getSpecPrice());
                gidtj.setPrice(new DecimalFormat("0.00").format(new BigDecimal(s.getSpecPrice()).multiply(new BigDecimal("1.25"))));
                gidtj.setVipPrice(new DecimalFormat("0.00").format(new BigDecimal(s.getSpecPrice()).multiply(new BigDecimal("1.12"))));
                gidtj.setGiveIntegral(new BigDecimal(gidtj.getVipPrice()).setScale(0, BigDecimal.ROUND_DOWN).intValue());
                gidtj.setIntegral(new BigDecimal(new DecimalFormat("0.00").format(new BigDecimal(s.getSpecPrice()).divide(new BigDecimal("0.07"), 6, BigDecimal.ROUND_HALF_UP))).setScale(0, BigDecimal.ROUND_UP).toString());
                gidtj.setShowCostingPrice(new DecimalFormat("0.00").format((new BigDecimal(gidtj.getVipPrice()).subtract(new BigDecimal(gidtj.getGiveIntegral()).multiply(new BigDecimal("0.07"))).subtract(new BigDecimal(s.getSpecPrice()))).multiply(new BigDecimal("0.7"))));
                gidtj.setGoodsCostingPrice(new BigDecimal(gidtj.getShowCostingPrice()).divide(new BigDecimal("0.7"), 2, RoundingMode.HALF_UP).toString());
                gidtj.setStartExpDate(s.getStartExpDate());
                gidtj.setEndExpDate(s.getEndExpDate());
                gidtj.setWeight(s.getWeight());
                list.add(gidtj);
            }
            dto.setVipPrice(new BigDecimal(new DecimalFormat("0.00").format(buyerPrice.multiply(new BigDecimal("1.12")))));
            dto.setIntegral(new BigDecimal(new DecimalFormat("0.00").format(buyerPrice.divide(new BigDecimal("0.07"), 6, BigDecimal.ROUND_HALF_UP))).setScale(0, BigDecimal.ROUND_UP).intValue());
            dto.setGoodsInventoryDetail(JSONArray.fromObject(list).toString());
            dto.setBuyerPrice(buyerPrice);
            dto.setGiveIntegral(dto.getVipPrice().setScale(0, BigDecimal.ROUND_DOWN).intValue());
            dto.setGoodsCostingPrice(new BigDecimal(new DecimalFormat("0.00").format((buyerPrice.multiply(new BigDecimal("1.12")).subtract(new BigDecimal(dto.getGiveIntegral()).multiply(new BigDecimal("0.07"))).subtract(buyerPrice)))));
            dto.setGoodsPrice(new BigDecimal(new DecimalFormat("0.00").format(buyerPrice.multiply(new BigDecimal("1.12")))));
            dto.setGoodsSaleNum((int) (Math.random() * (500 - 200 + 1) + 200));
            dto.setSeoKeywords(hn.getGoodsName());
            dto.setSeoDescription(hn.getGoodsName());
            dto.setStorePrice(buyerPrice);
            dto.setGoodsCurrentPrice(buyerPrice);
            dto.setGoodsBrief(hn.getGoodsName());
            GoodsImgDTO img = new GoodsImgDTO();
            img.setUrl("https://image.yilianbaihui.cn/consumer/" + TaoBaoUtils.uploadFile(hn.getPicLibUrl() + hn.getBig(), "", "upload/store/33307/" + DateHelper.getDate()));

            ArrayList<GoodsImgDTO> imgList = new ArrayList<>();
            imgList.add(img);
            dto.setMainImg(imgList);
            imgList.add(img);
            // 根据商品id查询轮播图id
            List<Long> photoId = goodsSpecService.selectPhotoIdByGoodsId(dto.getId());
            if (photoId.size() > 0) {
                if (photoId.size() >= 2) {
                    imgList.get(0).setId(photoId.get(0));
                    imgList.get(1).setId(photoId.get(1));
                } else {
                    imgList.get(0).setId(photoId.get(0));
                    imgList.get(1).setId(0L);
                }
            } else {
                imgList.get(0).setId(0L);
                imgList.get(1).setId(0L);
            }
            dto.setRollingImg(imgList);
            // 查询出该商品对应的库存
            dto.setGoodsInventory(stock);
            if (!StringUtils.isEmpty(hn.getDescription())) {
                dto.setGoodsDetails(hn.getDescription().replace("&lt;", "<"));
                dto.setGoodsDetails(dto.getGoodsDetails().replace("&gt;", ">"));
                dto.setGoodsDetails(dto.getGoodsDetails().replace("&quot;", "\""));
                dto.setGoodsDetails(dto.getGoodsDetails().replace("src=\"", "src=\"" + hn.getPicLibUrl().substring(0, hn.getPicLibUrl().length() - 1)));
                String template = "<style type=\\\"text/css\\\">*,:after,:before{box-sizing:border-box;margin:0;padding:0;word-wrap:break-word}.dc{padding-bottom:2.5rem;}p{color:#54565e;font-weight:300;font-size:14px;font-family:PingFangSC;line-height:25px}img{display:block;width:100%}video{width:100%;height:200px;}</style>";
                dto.setGoodsDetails(StringEscapeUtils.unescapeJava(template) + dto.getGoodsDetails());
            }
            HashMap<String, String> mmm = new HashMap<>();
            mmm.put("clientId", clientId);
            mmm.put("clientToken", clientToken);
            mmm.put("goodsSku", dto.getGoodsSerial());
            mmm.put("method", "goods.getPrice");
            String express = HttpUtils.sendPost(hnUrl, mmm);
            com.alibaba.fastjson.JSONObject hnprice = JSON.parseObject(express);
            String dataPrice = hnprice.getString("data");
            List<HNGoodsPrice> hnGoodsPrices = FastJsonUtil.toList(dataPrice, HNGoodsPrice.class);
            for (HNGoodsPrice hngp:hnGoodsPrices) {
                if (hngp.getNoDeliveryArea().size() > 0) {
                    String noDeliveryArea = StringEscapeUtils.unescapeJava(JSON.toJSONString(hngp.getNoDeliveryArea()));
                    noDeliveryArea = noDeliveryArea.replace("[\"","[");
                    noDeliveryArea = noDeliveryArea.replace("\"]","]");
                    noDeliveryArea = noDeliveryArea.replace("}\",\"", "},{");
                    dto.setNoDeliveryArea(noDeliveryArea);
                }
            }
            log.info("修改商品信息：" + dto);
            shoppingGoodsService.modifyGoodsById(dto, null);
        }
        return null;
    }

//    public void hnDeliverGoods(Map<String, Object> map) {
    public void hnDeliverGoods(HNExpressCallback hnec) {
//        String orderNo = (String) map.get("orderNo");
//        String goodsSku = (String) map.get("goodsSku");
//        String expressNo = (String) map.get("expressNo");
//        String deliveryTime = (String) map.get("deliveryTime");
        String orderNo = hnec.getOrderNo();
        String goodsSku = hnec.getGoodsSku();
        String expressNo = hnec.getExpressNo();
        String deliveryTime = hnec.getDeliveryTime();
        if (!StringUtils.isEmpty(orderNo)) {
            // 去查询子订单中商品数量
            List<SubOrderListVO> listVOS = shoppingOrderFormMapper.selectOrderCount(orderNo);
            String goodsName = "";
            if (listVOS.size() > 0) {
                // 购物车中候鸟的商品数量
                int count = 0;
                int goodsCart = 0;
                String spec = "";
                boolean isAll = true;
                for (SubOrderListVO vo : listVOS) {
                    if (vo.getEcId() != 0) {
                        // 说明是供应链商品
                        count = count + 1;
                        List<GoodsInventoryDetails> toList = FastJsonUtil.toList(vo.getName(), GoodsInventoryDetails.class);
                        for (GoodsInventoryDetails gids:toList) {
                            // 根据规格属性id查询属性名
                            String speName = shoppingGoodsMapper.selectSepcProperty(gids.getId().split("_")[0]);
                            // 获取规格信息的数值 正则表达式，用于匹配非数字串，+号用于匹配出多个非数字串
                            String regEx = "[^0-9]+";
                            Pattern pattern = Pattern.compile(regEx);
                            // 用定义好的正则表达式拆分字符串，把字符串中的数字留出来
                            String[] cs = pattern.split(speName);
                            String j = "";
                            if (cs.length > 0) {
                                j = cs.length > 1 ? cs[1] : Integer.valueOf(cs[0]).toString();
                            } else {
                                return;
                            }
                            if (goodsSku.equals(vo.getGoodsSerial()) && hnec.getGoodsSpecNum().equals(j)) {
                                // 说明是该商品发货
                                goodsCart = vo.getPayType();
                                goodsName = vo.getGoodsName();
                                spec = speName;
                            }
                        }

                    }
                }
                if (count != listVOS.size()) {
                    // 说明这个购物车中的商品不全是供应链的商品，只在子订单中写入物流信息
                    // 否则全是供应链的商品,大订单中写入订单物流信息
                    isAll = false;
                }

                // 根据候鸟的物流编码查询物流公司id
                List<ShoppingExpressCompanyVO> expressIds = shoppingOrderFormMapper.selectExpressIdByCode(hnec.getExpressCode());
                int expressId = 0;
                String expressCode = null;
                if (expressIds.size() > 0) {
                    expressId = expressIds.get(0).getId();
                    if (!StringUtils.isEmpty(expressIds.get(0).getCompanyMark())) {
                        expressCode = expressIds.get(0).getCompanyMark();
                    } else {
                        expressCode = expressIds.get(0).getCompanyCode();
                    }
                }

                // 根据候鸟推送修改物流信息
                if (isAll) {
                    // 修改主订单物流
                    shoppingOrderFormMapper.updateOrderFromExpressById(orderNo, expressNo, deliveryTime, expressId);
                }
                // 修改子订单物流
                shoppingOrderFormMapper.updateOrderExpressById(goodsCart, expressNo, deliveryTime, spec, expressId);

                // 修改第三方商品的订单状态为已发货
//                shoppingGoodsMapper.updateOrderData(hnec.getHnOrderNo());

                // 收货人信息
                OrderOrAddressVO ooa = shoppingOrderFormMapper.selectOrderAreaInfoByOrderNo(orderNo);

                // 给用户推送发货通知
                Map<String, String> map = new HashMap<>();
                map.put("userId", ooa.getUserId() + "");
                map.put("data", ooa.getId() + "");
                map.put("type", "9");
                map.put("stateStr", "已发货");
                map.put("pushContent", "");
                map.put("froms", "");
                HttpClientHelperUtils.sendHttpPosts(deliverGoods, map);

                // 发货对接快递鸟开始
                HashMap<String, String> map1 = new HashMap<>();
                map1.put("shipperCode", expressCode);
                map1.put("logisticCode", expressNo);
                map1.put("orderCode", orderNo);
                map1.put("receiptName", ooa.getTrueName());
                map1.put("receiptMobile", ooa.getMobile());
                map1.put("receiptCityName", ooa.getCity());
                map1.put("receiptProvinceName", ooa.getProvince());
                map1.put("receiptExpAreaName", ooa.getArea());
                map1.put("receiptAddress", ooa.getAreaInfo());
                map1.put("senderMobile", null);
                map1.put("senderName", null);
                map1.put("senderProvinceName", null);
                map1.put("senderCityName", null);
                map1.put("senderAddress", null);
                map1.put("senderExpAreaName", null);
                map1.put("goodsName", goodsName);
                String s = HttpClientHelperUtils.sendHttpPost(kdniao, map1);
                log.info("订阅快递鸟返回信息：" + s);
            }
        }
    }

    @Override
    public String modifyHNGoods() {
        ArrayList<String> goodsList = new ArrayList<>();
        goodsList = shoppingGoodsMapper.selectHNGoods();
        for (int i = 0; i < goodsList.size(); i++) {
            HashMap<String, String> m = new HashMap<>();
            m.put("clientId", clientId);
            m.put("clientToken", clientToken);
            m.put("method", "goods.getGoodsDetailBySku");
            m.put("goodsSku", goodsList.get(i));
            String sss = HttpUtils.sendPost(hnUrl, m);
            com.alibaba.fastjson.JSONObject jsonObject1 = JSON.parseObject(sss);
            JSONObject data = jsonObject1.getJSONObject("data");
            HouNiao hn = FastJsonUtil.toBean(data.getString("goodsDetail"), HouNiao.class);
            GoodsDTO dto = new GoodsDTO();
            dto.setGoodsSerial(hn.getSku());
            // 根据sku查询商品id
            int goodsId = shoppingGoodsMapper.selectGoodsIdBySku(dto.getGoodsSerial());
            dto.setId(Integer.valueOf(goodsId).longValue());
            JSONObject spec = JSON.parseObject(hn.getSpec().get(0));
            String hnSpec = "";
            for (Map.Entry<String, Object> entry : spec.entrySet()) {
                hnSpec = entry.getKey();
                break;
            }
//        String specJSONObject = spec.getString("基准");
            String specJSONObject = spec.getString(hnSpec);
            List<HNSpec> specs = FastJsonUtil.toList(specJSONObject, HNSpec.class);
            if (null != specs && specs.size() > 0) {
                List list = new ArrayList<GoodsInventoryDetailsToJsons>();
                // 售价
                BigDecimal buyerPrice = null;
                // 商品库存
                int stock = 0;
                for (HNSpec s : specs) {
                    // 根据候鸟的规格名去查询数据库中是否存在该规格
                    List<Integer> specId = goodsSpecService.getIsExistenceByName(s.getSpecDesc());
                    GoodsInventoryDetails gidtj = new GoodsInventoryDetails();
                    if (specId.size() > 0) {
                        // 说明数据库中已然存在同样的规格名
                        if (null == specId.get(0)) {
                            return "规格为空";
                        }
                        gidtj.setId(specId.get(0) + "_");
                    } else {
                        // 否则没有需要新建规格
                        SpecPropertyDTO spdto = new SpecPropertyDTO();
                        spdto.setSpecId(32797);
                        spdto.setName(s.getSpecDesc());
                        goodsSpecService.addSpec(spdto, new Date());
                        if (null == spdto.getId()) {
                            // 如果插入都没有返回id就去查
                            spdto = goodsSpecService.selectSpecIdByName(spdto);
                            if (null == spdto.getId()) {
                                return "新增规格为空";
                            }
                        }
                        gidtj.setId(spdto.getId() + "_");
                    }

                    // 取出最小的
                    if (null == buyerPrice) {
                        buyerPrice = new BigDecimal(s.getSpecPrice());
                    } else {
                        if (buyerPrice.compareTo(new BigDecimal(s.getSpecPrice())) == 1) {
                            buyerPrice = new BigDecimal(s.getSpecPrice());
                        }
                    }
                    if (stock == 0) {
                        stock = Integer.parseInt(s.getStock());
                    }
                    gidtj.setPriceType("2");
                    gidtj.setCount(s.getStock());
                    gidtj.setImgPath(hn.getPicLibUrl() + hn.getTiny());
                    gidtj.setBuyerPrice(s.getSpecPrice());
                    gidtj.setPrice(new DecimalFormat("0.00").format(new BigDecimal(s.getSpecPrice()).multiply(new BigDecimal("1.25"))));
                    gidtj.setVipPrice(new DecimalFormat("0.00").format(new BigDecimal(s.getSpecPrice()).multiply(new BigDecimal("1.12"))));
                    gidtj.setGiveIntegral(new BigDecimal(gidtj.getVipPrice()).setScale(0, BigDecimal.ROUND_DOWN).intValue());
                    gidtj.setIntegral(new BigDecimal(new DecimalFormat("0.00").format(new BigDecimal(s.getSpecPrice()).divide(new BigDecimal("0.07"), 6, BigDecimal.ROUND_HALF_UP))).setScale(0, BigDecimal.ROUND_UP).toString());
                    gidtj.setShowCostingPrice(new DecimalFormat("0.00").format((new BigDecimal(gidtj.getVipPrice()).subtract(new BigDecimal(gidtj.getGiveIntegral()).multiply(new BigDecimal("0.07"))).subtract(new BigDecimal(s.getSpecPrice()))).multiply(new BigDecimal("0.7"))));
                    gidtj.setGoodsCostingPrice(new BigDecimal(gidtj.getShowCostingPrice()).divide(new BigDecimal("0.7"), 2, RoundingMode.HALF_UP).toString());
                    gidtj.setStartExpDate(s.getStartExpDate());
                    gidtj.setEndExpDate(s.getEndExpDate());
                    gidtj.setWeight(s.getWeight());
                    list.add(gidtj);
                }
                dto.setVipPrice(new BigDecimal(new DecimalFormat("0.00").format(buyerPrice.multiply(new BigDecimal("1.12")))));
                dto.setIntegral(new BigDecimal(new DecimalFormat("0.00").format(buyerPrice.divide(new BigDecimal("0.07"), 6, BigDecimal.ROUND_HALF_UP))).setScale(0, BigDecimal.ROUND_UP).intValue());
                dto.setGoodsInventoryDetail(JSONArray.fromObject(list).toString());
                dto.setBuyerPrice(buyerPrice);
                dto.setGiveIntegral(dto.getVipPrice().setScale(0, BigDecimal.ROUND_DOWN).intValue());
                dto.setGoodsCostingPrice(new BigDecimal(new DecimalFormat("0.00").format((buyerPrice.multiply(new BigDecimal("1.12")).subtract(new BigDecimal(dto.getGiveIntegral()).multiply(new BigDecimal("0.07"))).subtract(buyerPrice)))));
                dto.setGoodsPrice(new BigDecimal(new DecimalFormat("0.00").format(buyerPrice.multiply(new BigDecimal("1.12")))));


                log.info("修改商品信息：" + dto);
                shoppingGoodsService.modifyGoodsById(dto, null);
            }
        }
        return null;
    }

    @Override
    public String modifyHNGoodsPriceOrCount() {
        List<GoodsDTO> lists = shoppingGoodsMapper.selectGoodsPriceOrCount();
        for (int i = 0; i < lists.size(); i++) {
            HashMap<String, String> m = new HashMap<>();
            m.put("clientId", clientId);
            m.put("clientToken", clientToken);
            m.put("method", "goods.getGoodsDetailBySku");
            m.put("goodsSku", lists.get(i).getGoodsSerial());
            String sss = HttpUtils.sendPost(hnUrl, m);
            com.alibaba.fastjson.JSONObject jsonObject1 = JSON.parseObject(sss);
            JSONObject data = jsonObject1.getJSONObject("data");
            HouNiao hn = FastJsonUtil.toBean(data.getString("goodsDetail"), HouNiao.class);
            GoodsDTO dto = new GoodsDTO();
            dto.setGoodsSerial(hn.getSku());
            // 根据sku查询商品id
            int goodsId = shoppingGoodsMapper.selectGoodsIdBySku(dto.getGoodsSerial());
            dto.setId(Integer.valueOf(goodsId).longValue());
            dto.setGoodsName(hn.getGoodsName());
            JSONObject spec = JSON.parseObject(hn.getSpec().get(0));
            String hnSpec = "";
            for (Map.Entry<String, Object> entry : spec.entrySet()) {
                hnSpec = entry.getKey();
                break;
            }
//        String specJSONObject = spec.getString("基准");
            String specJSONObject = spec.getString(hnSpec);
            List<HNSpec> specs = FastJsonUtil.toList(specJSONObject, HNSpec.class);
            if (null != specs && specs.size() > 0) {
                List list = new ArrayList<GoodsInventoryDetailsToJsons>();
                // 售价
                BigDecimal buyerPrice = null;
                // 商品库存
                int stock = 0;
                for (HNSpec s : specs) {
                    // 根据候鸟的规格名去查询数据库中是否存在该规格
                    List<Integer> specId = goodsSpecService.getIsExistenceByName(s.getSpecDesc());
                    GoodsInventoryDetails gidtj = new GoodsInventoryDetails();
                    if (specId.size() > 0) {
                        // 说明数据库中已然存在同样的规格名
                        if (null == specId.get(0)) {
                            return "规格为空";
                        }
                        gidtj.setId(specId.get(0) + "_");
                    } else {
                        // 否则没有需要新建规格
                        SpecPropertyDTO spdto = new SpecPropertyDTO();
                        spdto.setSpecId(32797);
                        spdto.setName(s.getSpecDesc());
                        goodsSpecService.addSpec(spdto, new Date());
                        if (null == spdto.getId()) {
                            // 如果插入都没有返回id就去查
                            spdto = goodsSpecService.selectSpecIdByName(spdto);
                            if (null == spdto.getId()) {
                                return "新增规格为空";
                            }
                        }
                        gidtj.setId(spdto.getId() + "_");
                    }

                    // 取出最小的
                    if (null == buyerPrice) {
                        buyerPrice = new BigDecimal(s.getSpecPrice());
                    } else {
                        if (buyerPrice.compareTo(new BigDecimal(s.getSpecPrice())) == 1) {
                            buyerPrice = new BigDecimal(s.getSpecPrice());
                        }
                    }
                    if (stock == 0) {
                        stock = Integer.parseInt(s.getStock());
                    }
                    gidtj.setPriceType("2");
                    gidtj.setCount(s.getStock());
                    gidtj.setImgPath(hn.getPicLibUrl() + hn.getTiny());
                    gidtj.setBuyerPrice(s.getSpecPrice());
                    gidtj.setPrice(new DecimalFormat("0.00").format(new BigDecimal(s.getSpecPrice()).multiply(new BigDecimal("1.25"))));
                    gidtj.setVipPrice(new DecimalFormat("0.00").format(new BigDecimal(s.getSpecPrice()).multiply(new BigDecimal("1.12"))));
                    gidtj.setGiveIntegral(new BigDecimal(gidtj.getVipPrice()).setScale(0, BigDecimal.ROUND_DOWN).intValue());
                    gidtj.setIntegral(new BigDecimal(new DecimalFormat("0.00").format(new BigDecimal(s.getSpecPrice()).divide(new BigDecimal("0.07"), 6, BigDecimal.ROUND_HALF_UP))).setScale(0, BigDecimal.ROUND_UP).toString());
                    gidtj.setShowCostingPrice(new DecimalFormat("0.00").format((new BigDecimal(gidtj.getVipPrice()).subtract(new BigDecimal(gidtj.getGiveIntegral()).multiply(new BigDecimal("0.07"))).subtract(new BigDecimal(s.getSpecPrice()))).multiply(new BigDecimal("0.7"))));
                    gidtj.setGoodsCostingPrice(new BigDecimal(gidtj.getShowCostingPrice()).divide(new BigDecimal("0.7"), 2, RoundingMode.HALF_UP).toString());
                    gidtj.setStartExpDate(s.getStartExpDate());
                    gidtj.setEndExpDate(s.getEndExpDate());
                    gidtj.setWeight(s.getWeight());
                    list.add(gidtj);
                }

                // 对比商品之前的规格信息，如果有多的规格信息就将其删除
                List<HNSpecVO> goodsIdAndSpecId = shoppingGoodsMapper.selectGoodsIdOrSpecIdByGoodsId(goodsId);
                for (int j = 0; j < specs.size(); j++) {
                    for (int k = 0; k < goodsIdAndSpecId.size(); k++) {
                        if (specs.get(j).getSpecDesc().equals(goodsIdAndSpecId.get(k).getSpecName())) {

                        }
                    }
                }

                dto.setVipPrice(new BigDecimal(new DecimalFormat("0.00").format(buyerPrice.multiply(new BigDecimal("1.12")))));
                dto.setIntegral(new BigDecimal(new DecimalFormat("0.00").format(buyerPrice.divide(new BigDecimal("0.07"), 6, BigDecimal.ROUND_HALF_UP))).setScale(0, BigDecimal.ROUND_UP).intValue());
                dto.setGoodsInventoryDetail(JSONArray.fromObject(list).toString());
                dto.setBuyerPrice(buyerPrice);
                dto.setGiveIntegral(dto.getVipPrice().setScale(0, BigDecimal.ROUND_DOWN).intValue());
                dto.setGoodsCostingPrice(new BigDecimal(new DecimalFormat("0.00").format((buyerPrice.multiply(new BigDecimal("1.12")).subtract(new BigDecimal(dto.getGiveIntegral()).multiply(new BigDecimal("0.07"))).subtract(buyerPrice)))));
                dto.setGoodsPrice(new BigDecimal(new DecimalFormat("0.00").format(buyerPrice.multiply(new BigDecimal("1.12")))));
                dto.setGoodsSaleNum((int) (Math.random() * (500 - 200 + 1) + 200));
                dto.setSeoKeywords(hn.getGoodsName());
                dto.setSeoDescription(hn.getGoodsName());
                dto.setStorePrice(buyerPrice);
                dto.setGoodsCurrentPrice(buyerPrice);
                dto.setGoodsBrief(hn.getGoodsName());
                GoodsImgDTO img = new GoodsImgDTO();
                img.setUrl("https://image.yilianbaihui.cn/consumer/" + TaoBaoUtils.uploadFile(hn.getPicLibUrl() + hn.getBig(), "", "upload/store/33307/" + DateHelper.getDate()));

                ArrayList<GoodsImgDTO> imgList = new ArrayList<>();
                imgList.add(img);
                dto.setMainImg(imgList);
                imgList.add(img);
                // 根据商品id查询轮播图id
                List<Long> photoId = goodsSpecService.selectPhotoIdByGoodsId(dto.getId());
                if (photoId.size() > 0) {
                    if (photoId.size() >= 2) {
                        imgList.get(0).setId(photoId.get(0));
                        imgList.get(1).setId(photoId.get(1));
                    } else {
                        imgList.get(0).setId(photoId.get(0));
                        imgList.get(1).setId(0L);
                    }
                } else {
                    imgList.get(0).setId(0L);
                    imgList.get(1).setId(0L);
                }
                dto.setRollingImg(imgList);
                // 查询出该商品对应的库存
                dto.setGoodsInventory(stock);
                if (!StringUtils.isEmpty(hn.getDescription())) {
                    dto.setGoodsDetails(hn.getDescription().replace("&lt;", "<"));
                    dto.setGoodsDetails(dto.getGoodsDetails().replace("&gt;", ">"));
                    dto.setGoodsDetails(dto.getGoodsDetails().replace("&quot;", "\""));
                    dto.setGoodsDetails(dto.getGoodsDetails().replace("src=\"", "src=\"" + hn.getPicLibUrl().substring(0, hn.getPicLibUrl().length() - 1)));
                    String template = "<style type=\\\"text/css\\\">*,:after,:before{box-sizing:border-box;margin:0;padding:0;word-wrap:break-word}.dc{padding-bottom:2.5rem;}p{color:#54565e;font-weight:300;font-size:14px;font-family:PingFangSC;line-height:25px}img{display:block;width:100%}video{width:100%;height:200px;}</style>";
                    dto.setGoodsDetails(StringEscapeUtils.unescapeJava(template) + dto.getGoodsDetails());
                }
                HashMap<String, String> mmm = new HashMap<>();
                mmm.put("clientId", clientId);
                mmm.put("clientToken", clientToken);
                mmm.put("goodsSku", dto.getGoodsSerial());
                mmm.put("method", "goods.getPrice");
                String express = HttpUtils.sendPost(hnUrl, mmm);
                com.alibaba.fastjson.JSONObject hnprice = JSON.parseObject(express);
                String dataPrice = hnprice.getString("data");
                List<HNGoodsPrice> hnGoodsPrices = FastJsonUtil.toList(dataPrice, HNGoodsPrice.class);
                for (HNGoodsPrice hngp : hnGoodsPrices) {
                    if (hngp.getNoDeliveryArea().size() > 0) {
                        String noDeliveryArea = StringEscapeUtils.unescapeJava(JSON.toJSONString(hngp.getNoDeliveryArea()));
                        noDeliveryArea = noDeliveryArea.replace("[\"", "[");
                        noDeliveryArea = noDeliveryArea.replace("\"]", "]");
                        noDeliveryArea = noDeliveryArea.replace("}\",\"", "},{");
                        dto.setNoDeliveryArea(noDeliveryArea);
                    }
                }
                log.info("修改商品信息：" + dto);
                shoppingGoodsService.modifyGoodsById(dto, null);
            }
        }
        return null;
    }
}
